﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web.Http;
using System.Web.Mvc;

using Microsoft.Practices.Unity;

using ERPStore.Extensions;
using ERPStore.Web.Routing;

using EventBrokR;

namespace ERPStore.Indexers.Lucene
{
	public class PluginInit : ERPStore.Extensibility.PluginInit
	{
		public PluginInit()
		{
			Container = GlobalConfiguration.Configuration.DependencyResolver.GetContainer();
		}

		Microsoft.Practices.Unity.IUnityContainer Container { get; set; }

		[Dependency]
		public ERPStore.Logging.ILogger Logger { get; set; }

		public override void AddServices()
		{
			base.AddServices();

			var settings = new Models.Settings();
			settings.BindFromConfiguration(ERPStore.Indexers.Lucene.Configuration.ConfigurationSettings.AppSettings);
			Container.RegisterInstance<Models.Settings>(settings, new ContainerControlledLifetimeManager());

			// Container.RegisterType<Services.ReindexEventMessage>("reindexfulltextcatalog");
			Container.RegisterType<global::Lucene.Net.Analysis.Analyzer, Services.StoreAnalyzer>();
			Container.RegisterType<Services.ICompensatorRepository, Services.FileCompensatorRepository>();
			Container.RegisterType<Services.IndexBuilder>(new ContainerControlledLifetimeManager()); // Singleton
			Container.RegisterType<Repositories.LuceneRepository>(new ContainerControlledLifetimeManager());

			var eb = Container.Resolve<EventBrokR.IPublisher>();
			eb.Container.Register<EventConsumers.EndApplicationRequestedEventConsumer>();
		}

		public override void Load()
		{
			base.Load();
			var settings = Container.Resolve<Models.Settings>();
			var taskService = Container.Resolve<ERPStore.Services.IScheduledTaskService>();

			// Creation de l'index fulltext
			if (settings.EnableScheduledIndexation)
			{
				var fullTextIndexTask = TaskHelper.CreateIndexationTask();
				taskService.Add(fullTextIndexTask);
			}
			else
			{
				var builder = GlobalConfiguration.Configuration.DependencyResolver.GetService<Services.IndexBuilder>();
				builder.EnableLuceneCatalogService();
			}
		}

		public override void RegisterRoutes()
		{
			var namespaces = new string[] { "ERPStore.Indexers.Lucene.Controllers" };

			RouteTable.Routes.MapERPStoreRoute(
				"LuceneCatalogService"
				, "admin/lucene/{action}"
				, new { controller = "LuceneCatalog", action = "Index" }
				, namespaces
			);

			RouteTable.Routes.MapHttpRoute(
				"LuceneApi"
				, "api/lucene/{action}/{id}"
				, new { controller = "LuceneApi", action = UrlParameter.Optional, id = UrlParameter.Optional }
			);
		}
	}
}
